﻿
using Chemistry.Models;
using Chemistry.Tools;
using GalaSoft.MvvmLight.Command;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace Chemistry.ViewModels
{
    public class LoginViewModel:VmBase
    {
        private string version;
        private readonly IDialogCoordinator _dialogCoordinator;
        ProgressDialogController controller = null;
        public string ClientName { get; set; }

        public LoginViewModel(DialogCoordinator dialogCoordinator)
        {
            this._dialogCoordinator = dialogCoordinator;
            ClientName = GetClientName();
            CommitCommand = new RelayCommand(Execute, CanExecute);
        }

  
        string GetClientName()
        {
            string value = "";
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = config.AppSettings.Settings;
                var item = settings["ClientName"];
                if (item == null)
                {
                    config.AppSettings.Settings.Add("ClientName", "");
                }
                else
                {
                    value = item.Value;
                }

                var versionitem = settings["VERSION"];
                if (versionitem != null)
                {
                    version = versionitem.Value;
                }
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);

            }

            return value;
        }
        

        private bool CanExecute()
        {
            return !String.IsNullOrEmpty(ClientName);
        }

        private async void Execute()
        {
            await LoginAsync();
        }

        private async Task LoginAsync()
        {
            controller = await _dialogCoordinator.ShowProgressAsync(this, "登录中...", "");
            controller.SetIndeterminate();
            string password = "0";//GetPassword();
            string url = string.Format("Login?name={0}&password={1}", ClientName, password);
            try
            {
                var result = await HttpBasePrimary.PostAsJsonAsync<ResultData>(url, null);
                if (result.status == 0 && !string.IsNullOrEmpty(result.session))
                {
                    HttpBasePrimary.Session = result.session;
                    SaveClientName();
                    Global.ClientName = ClientName;
                    ServerLogTool.UploadLog("登录系统" + " 版本：" + version, EventType.Information);
                    LogTool.WriteInfoLog("登录系统" + " 版本：" + version);
                    Send<object>(null, MessageToken.ShowMainWindow);
                   
                }
                else if (result.status == 1)
                {
                    await controller.CloseAsync();
                    await _dialogCoordinator.ShowMessageAsync(this, "提示", "用户名或密码错误");
                    //MessageBox.Show("用户名或密码错误，请联系管理员", "提示", MessageBoxButton.OK);
                }
                else if (result.status == -3)
                {
                    await controller.CloseAsync();
                    await _dialogCoordinator.ShowMessageAsync(this, "提示", "服务器异常，请联系管理员");
                    //MessageBox.Show("服务器异常，请联系管理员", "提示", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                string message = string.Empty;
                GetMessage(ex, ref message);
                LogTool.WriteErrorLog(message, ex);
                Show(message);
                //MessageBox.Show(message, "提示", MessageBoxButton.OK);
            }
        }

        private async void Show(string msg)
        {

            await controller.CloseAsync();
            await _dialogCoordinator.ShowMessageAsync(this, "提示", "登陆异常:" + msg);
        }

        private void GetMessage(Exception ex, ref string msg)
        {
            if (ex.InnerException != null)
            {
                GetMessage(ex.InnerException, ref msg);
            }
            else
            {
                msg = ex.Message;
            }
        }

        string GetPassword()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                return (from ManagementObject mo in searcher.Get() select mo["SerialNumber"].ToString().Trim()).FirstOrDefault();
            }
            catch
            {
                return "";
            }
        }

        private void SaveClientName()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["ClientName"].Value = this.ClientName;
            config.Save();
        }
    }
}
